import { Controller, HttpCode, HttpStatus, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { AttachmentService } from './attachment.service';
import { Express, Request } from 'express';
import { Public } from 'src/auth/decorators/public.decorator';
import { diskStorage } from 'multer';
const crypto = require('crypto');
import fs from 'fs'
const Readable = require('stream').Readable
const stream = require('stream')
// import stream from 'stream'

@Controller('attachment')
export class AttachmentController {
  constructor(private readonly attachmentService: AttachmentService) {}

  @Post('upload')
  @HttpCode(HttpStatus.OK)
  @Public()
  @UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
      destination: (req: Request, file, cb) => {
        const { groupId } = req.body
        cb(null, `public/${groupId}`)
      },
      filename: async (req: Request, file, cb) => {
        const fileStream = new Readable(file.stream);
        fileStream.push(null)
        const stream1 = fileStream.pipe(new stream.PassThrough())
        const hash = crypto.createHash('md5');
        const suffix = file.originalname.split('.')[1];
        stream1.on('data', chunk => {
          hash.update(chunk, 'utf-8');
        });
        stream1.on('end', () => {
          const md5 = hash.digest('hex');
          cb(null, `${md5}.${suffix}`);
        });
      }
    })
  }))
  upload(@UploadedFile() file: Express.Multer.File) {
    return this.attachmentService.upload(file)
  }
}
